<?php

namespace Home\Controller;

use Home\Model\UserModel;
use Think\Controller;

class AuthController extends Controller
{

    /**
     * 验证码
     */
    public function verify()
    {
        $Verify = new \Think\Verify();
        $Verify->entry();
    }

    /*
     *  检查验证码
     */
    function check_verify($code, $id = '')
    {
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }

    /**
     * 登录界面
     */
    public function login()
    {
        return $this->display();
    }

    public function loginLogic()
    {
        $flag = $this->check_verify(I('post.code'));
        if (!$flag) {
            return $this->retError('验证码错误');
        }

        $User = M("User"); // 实例化User对象
        $map['name'] = I('post.name');
        $map['role'] = I('post.role');
        $result = $User->where($map)->select();

        if (!$result) {
            return $this->retError('账号密码不正确');
        } else {
            if ($result[0]['password'] == I('post.password')) {
                session('user', $result[0]);
                return $this->retSuccess();
            } else {
                return $this->retError('账号密码不正确');
            }

        }
    }


    /**
     * 注册用户
     * Author: 陈坤
     * Date: 2019/11/26 15:43
     */
    public function register()
    {

        $User = new UserModel(); // 实例化User对象
        $map['name'] = I('post.name');
        $result = $User->where($map)->select();
        if ($result) {
            $this->retError('用户名已存在');
        }

        $data = I('post.');
        $data['create_time'] = time();
        $data['update_time'] = time();

        $User->create($data);
        $result = $User->add();
        if (!$result) {
            $this->retError('账号密码不正确');
        } else {
            $this->retSuccess();
        }
    }


    public function loginOut()
    {
        session('user', null);
        return redirect('/home/auth/login');
    }

    protected function retSuccess()
    {
        $data['code'] = 0;
        $data['msg'] = '操作成功';
        $this->ajaxReturn($data);
    }

    protected function retError($msg)
    {
        $data['code'] = -1;
        $data['msg'] = $msg;
        $this->ajaxReturn($data);
    }
}